/*
 * Copyright 2025 arisgo@163.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.arisgo.cloud.flux.mybatis.utils;

import com.arisgo.cloud.common.utils.ArgsUtil;
import com.arisgo.cloud.common.utils.StringUtil;
import com.arisgo.cloud.flux.mybatis.model.ITree;

import java.util.List;

/**
 * @author Coulson
 * @since 2023-7-2
 */
public class TreeUtil {

    public static final String ROOT_CODE = "0";

    public static <T extends ITree<T>> List<T> convertTree(String code, List<T> data) {
        if (ArgsUtil.isEmpty(data)) {
            return data;
        }
        String rootCode = !StringUtil.hasLength(code) ? ROOT_CODE : code;
        List<T> nodes = data.stream().filter(c -> rootCode.equals(c.getParentCode())).toList();
        setChildren(nodes, data);
        return nodes;
    }

    public static <T extends ITree<T>> void setChildren(List<T> nodes, List<T> data) {
        if (ArgsUtil.isEmpty(nodes) || ArgsUtil.isEmpty(data)) {
            return;
        }
        data.removeAll(nodes);
        for (T node : nodes) {
            List<T> children = data.stream().filter(c -> node.getCode().equals(c.getParentCode())).toList();
            if (!ArgsUtil.isEmpty(children)) {
                setChildren(children, data);
                node.setChildren(children);
            }
        }
    }

}
